package com.yyk.yiliao.ui.activity.detail.fragment;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseFragment;
import com.yyk.yiliao.base.BaseRecyclerAdapter;
import com.yyk.yiliao.base.BaseRecyclerHolder;
import com.yyk.yiliao.ui.activity.detail.activity.PayPleaceOrder_Activity;
import com.yyk.yiliao.ui.activity.detail.activity.ShAdressGl_Activity;
import com.yyk.yiliao.bean.CartCartpay_Info;
import com.yyk.yiliao.ui.activity.shopcart.ArrayBean;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.widget.diver.more.SpacesItemDecoration;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.OrderSubOrder_Info;
import com.yyk.yiliao.widget.diver.CustomDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 提交订单
 */

public class PleaceOrder_Fragment extends BaseFragment {

    private static final String ARGS_PAGE = "PleaceOrder_Fragment";
    @BindView(R.id.xzshdz)
    LinearLayout xzshdz;

    @BindView(R.id.rv_proder_one)
    RecyclerView rvProderOne;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.rl_wudizhi)
    RelativeLayout rlWudizhi;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.rl_youdizhi)
    RelativeLayout rlYoudizhi;
    @BindView(R.id.setting)
    RelativeLayout setting;
    @BindView(R.id.tv_total)
    TextView tvTotal;
    @BindView(R.id.tv_total_price)
    TextView tvTotalPrice;
    @BindView(R.id.et_beizhu)
    EditText etBeizhu;
    private String json; //订单提交需要上传的参数
    private int sub_type;
    private String addressidBack;
    private int type; // 快递上门 1，货到付款2
    private CartCartpay_Info info;


    public static PleaceOrder_Fragment newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(ARGS_PAGE, page);
        PleaceOrder_Fragment fragment = new PleaceOrder_Fragment();
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * Activity 向 fragment 中传的值
     * 地址信息
     *
     * @param info
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Shadressgl(ShAdressGl_Activity.PleaceOrder_One info) {
        if (info != null) {
            rlYoudizhi.setVisibility(View.VISIBLE);
            rlWudizhi.setVisibility(View.GONE);
        }
        String address = info.getAddress();
        tvAddress.setText(address);
        tvName.setText(info.getName());
        tvPhone.setText(info.getPhone());
        addressidBack = info.getId();
        Logger.e("addressidBack" + addressidBack);
    }

    /**
     * 商品信息
     *
     * @param info
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void omMessage(CartCartpay_Info info) {
        Logger.e("订单确认信息" + info.toString());
        this.info = info;
        sub_type = info.getSub_type();
        if (info.getCode() == 1) {
            //TODO 外部价格
            tvTotal.setText("¥" + info.getTotal());
            tvTotalPrice.setText("¥" + info.getTotal());
            // TODO 默认 地址
            CartCartpay_Info.AddressBean addres = info.getAddress();
            initAddress(addres);
            //TODO 中部商品
            List<CartCartpay_Info.DataBean> data = info.getData();
            initCartCartpay(data);

        }

    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_porder_one;
    }

    @Override
    public void initView() {
        initPost();
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 有地址添加上去
     *
     * @param address
     */
    private void initAddress(CartCartpay_Info.AddressBean address) {
        Logger.e("填写订单地址" + address);
        if (address != null) {
            rlYoudizhi.setVisibility(View.VISIBLE);
            rlWudizhi.setVisibility(View.GONE);
            tvName.setText(address.getName());
            tvPhone.setText(address.getPhone());
            tvAddress.setText(address.getProvince_name() + " " + address.getCounty_name() + " " + address.getCity_name() + " " + address.getAddress());
        } else {
            rlYoudizhi.setVisibility(View.GONE);
            rlWudizhi.setVisibility(View.VISIBLE);
        }
    }

    private void initCartCartpay(final List<CartCartpay_Info.DataBean> data) {

        BaseRecyclerAdapter<CartCartpay_Info.DataBean> adapter = new BaseRecyclerAdapter<CartCartpay_Info.DataBean>(getContext(), data, R.layout.adapter_item_place_one) {
            @Override
            public void convert(BaseRecyclerHolder holder, CartCartpay_Info.DataBean item, int position, boolean isScrolling) {
                holder.setText(R.id.tv, item.getSname());
                LinearLayout ll_kuaidi = holder.getView(R.id.ll_kuaidi);
                ll_kuaidi.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //默认 快递包邮
//                        changeIcon();
                    }
                });
                RecyclerView rv = holder.getView(R.id.rv);
                rv.addItemDecoration(new CustomDecoration(getActivity(), CustomDecoration.VERTICAL_LIST, R.drawable.divider_item_ef_1, 0));
                rv.setLayoutManager(new LinearLayoutManager(getContext()));
                rv.setAdapter(new BaseRecyclerAdapter<CartCartpay_Info.DataBean.GoodslistBean>(getContext(), item.getGoodslist(), R.layout.adapter_item_place_one_one) {
                    @Override
                    public void convert(BaseRecyclerHolder holder, CartCartpay_Info.DataBean.GoodslistBean item, int position, boolean isScrolling) {
                        holder.setText(R.id.tv, item.getName());
                        holder.setText(R.id.tv2, "¥" + item.getMoney());
                        holder.setText(R.id.tv3, "X" + item.getNum());
                        holder.setImageByUrl(R.id.iv, ApiService.BASE_URL + item.getImg());

                    }
                });
            }
        };
        rvProderOne.addItemDecoration(new CustomDecoration(getActivity(), CustomDecoration.VERTICAL_LIST, R.drawable.divider_item_ef_15, 0));
        rvProderOne.addItemDecoration(new SpacesItemDecoration(0, 30));
        rvProderOne.setLayoutManager(new LinearLayoutManager(getContext()));
        rvProderOne.setAdapter(adapter);
    }


    /**
     * 1.商品数据列表
     */
    private void initPost() {
    }


    // 声明PopupWindow
    private PopupWindow popupWindow;
    // 声明PopupWindow对应的视图
    private View popupView;

    // 声明平移动画
    private TranslateAnimation animation;

    /**
     * 弹出popupWindow快递选择
     */
    private void changeIcon() {
        if (popupWindow == null) {
            popupView = View.inflate(getActivity(), R.layout.dialog_pleaceorder_one, null);
            // 参数2,3：指明popupwindow的宽度和高度
            popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT);
            final RadioButton radio = popupView.findViewById(R.id.radio);
            RadioButton radio2 = popupView.findViewById(R.id.radio2);
            RadioGroup rg_group = popupView.findViewById(R.id.rg_group);
            rg_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    switch (checkedId) {
                        case R.id.radio:
                            Hawk.put("pl_type", 1);
                            break;
                        case R.id.radio2:
                            Hawk.put("pl_type", 2);
                            break;
                    }
                }
            });

            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                }
            });

            // 设置背景图片， 必须设置，不然动画没作用
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            popupWindow.setFocusable(true);

            // 设置点击popupwindow外屏幕其它地方消失
            popupWindow.setOutsideTouchable(true);

            // 平移动画相对于手机屏幕的底部开始，X轴不变，Y轴从1变0
            animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 0,
                    Animation.RELATIVE_TO_PARENT, 1, Animation.RELATIVE_TO_PARENT, 0);
            animation.setInterpolator(new AccelerateInterpolator());
            animation.setDuration(500);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowManager.LayoutParams lp = getActivity().getWindow()
                            .getAttributes();
                    lp.alpha = 1.0f;
                    getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                    getActivity().getWindow().setAttributes(lp);
                }
            });
            popupView.findViewById(R.id.queding).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();

                }
            });
        }
        //设置背景透明
        // 产生背景变暗效果
        WindowManager.LayoutParams lp = getActivity().getWindow()
                .getAttributes();
        lp.alpha = 0.5f;
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getActivity().getWindow().setAttributes(lp);
        // 在点击之后设置popupwindow的销毁
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        }


        // 设置popupWindow的显示位置，此处是在手机屏幕底部且水平居中的位置
        popupWindow.showAtLocation(getActivity().findViewById(R.id.setting), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        popupView.startAnimation(animation);
    }


    @OnClick({R.id.xzshdz, R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.xzshdz:
                Intent intent = new Intent(getContext(), ShAdressGl_Activity.class);
                startActivity(intent);
                break;
            case R.id.tv_commit:
                String tvAddress = this.tvAddress.getText().toString().trim();
                String tvPphone = this.tvPhone.getText().toString().trim();
                String tvName = this.tvName.getText().toString().trim();
                if (TextUtils.isEmpty(tvAddress) && TextUtils.isEmpty(tvPphone) && TextUtils.isEmpty(tvName)) {
                    ToastUtil.showShort(getActivity(), "请重新选择地址");

                    return;
                }
                List<CartCartpay_Info.DataBean> carList = info.getData();
                CartCartpay_Info.AddressBean address = info.getAddress();
                ArrayBean arrayBean = new ArrayBean();

                if (address != null) {
                    int addressid = address.getId();
                    arrayBean.setAddrid(addressid);
                } else {
                    if (!TextUtils.isEmpty(addressidBack)) {
                        arrayBean.setAddrid(Integer.parseInt(addressidBack));
                    }
                }
                String etBeizhu = this.etBeizhu.getText().toString().trim();
                arrayBean.setText(etBeizhu);
                List<ArrayBean.DataBean> dataList = new ArrayList<>();
                for (int i = 0; i < carList.size(); i++) {
                    List<CartCartpay_Info.DataBean.GoodslistBean> goodslist = carList.get(i).getGoodslist();
                    for (int j = 0; j < goodslist.size(); j++) {
                        ArrayBean.DataBean bean = new ArrayBean.DataBean();
                        int cartid = goodslist.get(j).getCartid();//cartid   购物车订单号
                        bean.setCartid(String.valueOf(cartid));
                        bean.setType(1);  //  TODO 配送方式  需要自己 传值  默认快递包邮
                        dataList.add(bean);
                    }
                }
                arrayBean.setData(dataList);
                Gson gson = new Gson();
                json = gson.toJson(arrayBean, ArrayBean.class);
                // 收货地址
                Logger.e("转换数据" + json.toString());
                Map<String, String> map = new TreeMap<>();
                map.put("data", json);
                map.put("sub_type", sub_type + "");  //订单来源
                map.put("sign", Md5Util2.createSign(map));
                Logger.e("sub_type___" + sub_type);//提交来源 1.购物车结算，重新下单
                RxUtils.getInstance().retrofit.create(ApiService.class).postOrderSubOrder(map)
                        .subscribeOn(Schedulers.io())     //调度线程
                        .observeOn(AndroidSchedulers.mainThread())
                        .unsubscribeOn(Schedulers.io())   //取消订阅
                        .subscribe(new Subscriber<OrderSubOrder_Info>() {

                            @Override
                            public void onCompleted() {
                            }

                            @Override
                            public void onError(Throwable e) {
                                Logger.e("www" + e.getLocalizedMessage() + e.getMessage());
                            }

                            @Override
                            public void onNext(OrderSubOrder_Info info) {
                                Logger.e("购物车提交订单" + info.getMsg());
                                if (info.getCode() == 1) {
                                    Bundle bundle = new Bundle();
                                    //1. 购物车结算呢
                                    bundle.putString("endtype", "1");
                                    bundle.putString("out_trade_no", info.getData().getOrder_code() + "");
                                    bundle.putString("total", info.getData().getTotal() + "");
                                    bundle.putString("addtime", info.getData().getAddtime() + "");
                                    startAct(PayPleaceOrder_Activity.class, true, bundle);
                                } else if (info.getCode() == 106) {
                                    ToastUtil.showShort(getActivity(), info.getMsg());
                                } else if (info.getCode() == 107) {
                                    ToastUtil.showShort(getActivity(), info.getMsg());
                                } else if (info.getCode() == 108) {
                                    ToastUtil.showShort(getActivity(), info.getMsg());
                                } else if (info.getCode() == 109) {
                                    ToastUtil.showShort(getActivity(), info.getMsg());
                                }
                            }
                        });
                break;

        }
    }


}
